package com.sgl.util;

import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public class ExportUtilTEST<T> {

    public  void exportExcelUtil(String fileName, String[] columName, List<T> data, HttpServletResponse response) throws IllegalAccessException, IOException {


        //创建一个excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        //文件名
        HSSFSheet sheet = workbook.createSheet(fileName);
        //在excel表中添加表头
        HSSFRow row = sheet.createRow(0);
        //循环遍历 给表头赋值
        for (int i = 0; i < columName.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(columName[i]);
            cell.setCellValue(text);
        }

        //循环遍历 数据 给每一个列赋值
        //从第一行开始
        int rowNum = 1;
        int columSize = columName.length;
        T t = null;
        //Class<CommonPackage> aClass =T;
        //fields = t.getClass().getDeclaredFields();
        Class  tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Field[] declaredFields =t.getClass().getDeclaredFields();
        if (declaredFields[0].getName().equals("id")) {
            for (T item : data) {
                HSSFRow row1 = sheet.createRow(rowNum);
                for (int i = 0; i < columSize; i++) {
                    //反射获取每个成员变量的返回值
                    row1.createCell(i).setCellValue((String) declaredFields[i + 1].get(item));
                }
                rowNum++;

            }
        }
      /*  response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());*/

     FileOutputStream output=new FileOutputStream("D:\\test7.xls");
        workbook.write(output);
        output.flush();
        output.close();

    }

}
